<template>
  <div>
    <div>
      <input type="text" v-model="user.id">
      <input type="text" v-model="user.name">
      <button @click="addItem">提交</button>
    </div>
    <ul>
      <li v-for="item in state.arr" :key="item.id" @click="handleDelete(item.id)">{{item.name}}</li>
    </ul>
  </div>
</template>

<script>
import { reactive } from 'vue'

export default {
  setup() {
    // !reactive 可以包装对象为响应式的数据
    const state = reactive({
      arr: [
        {
          id: 0,
          name: 'ifer',
        },
        {
          id: 1,
          name: 'elser',
        },
        {
          id: 2,
          name: 'xxx',
        },
      ],
    })
    const handleDelete = (id) => {
      // 根据 id 找索引
      const idx = state.arr.findIndex(item => item.id === id)
      // 根据索引去删除
      state.arr.splice(idx, 1)
    }

    // !#1 先收集数据
    const user = reactive({
      id: '',
      name: ''
    })
    const addItem = () => {
      // state.arr.push(user) // 错误
      /* state.arr.push({
        id: user.id,
        name: user.name
      }) */
      // state.arr.push(Object.assign({}, user))
      state.arr.push({
        ...user
      })
      // 清空输入的数据
      user.id = ''
      user.name = ''
      // !注意点
      // 不要直接下面写法，
      // user = {}
      // user = reactive({})
    }
    return {
      state,
      handleDelete,
      user,
      addItem
    }
  }
}

/* const o = { age: 18 }
const arr = []
arr.push(o)
o.age = 19
console.log(arr) // ?? */

</script>

<style lang="scss" scoped></style>